package it.oneb.study.servlet;

import it.oneb.study.mysql.DbConfig;
import it.oneb.study.spring.HelloWorld;
import it.oneb.study.spring.SpringContextHolder;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloServlet extends HttpServlet
{

	@Override
	public void init(ServletConfig config) throws ServletException
	{
		super.init(config);
		
		initSpring();
		
	}
	
	@Override
	public void service(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		
		response.setContentType("text/html;charset=UTF-8");
		
		
		// 获取输出流
		PrintWriter out = response.getWriter();
		HelloWorld helloSpring = (HelloWorld) getService("helloBean");
		out.println("<html><body>hello, world3" + queryNameFromDb() + helloSpring.getName()+"</body></html>");
		
	}
	
	
	/**
	 * 初始化加载spring的bean
	 */
	private void initSpring()
	{
		// 根据classpath下面的配置文件创建context
		
		SpringContextHolder.context = new ClassPathXmlApplicationContext("bean.xml");  

		System.out.println("Spring inited");
	}
	
	
	/**
	 * 获取某个bean
	 * @param serviceName
	 * @return
	 */
	private Object getService(String serviceName)
	{
		return SpringContextHolder.context.getBean(serviceName);
	}
	
	
	/**
	 * DAO
	 * @return
	 */
	private String queryNameFromDb()
	{
		String jdbcUrl = "jdbc:mysql://localhost:3306/test?user=root&password=123456";
		String sql = "select * from user";
		String name = null;
		DbConfig dbConfig = new DbConfig(jdbcUrl);
		dbConfig.openConnection();


		ResultSet resultSet = dbConfig.querySql(sql);
		try {
			while(resultSet.next()){

				name = resultSet.getString("NAME");
			}
		} catch (SQLException e) {
			System.out.println(e.getMessage());
		}

		dbConfig.closeConnection();
		return name;
	}
}
